package com.yixun.qfbao.job;

import com.alibaba.fastjson.JSONObject;
import com.yixun.qfbao.apidto.v10dto.BaseResponseDto;
import com.yixun.qfbao.model.ApiLog;
import com.yixun.qfbao.model.ApiLogSendV10Again;
import com.yixun.qfbao.model.OtherCompany;
import com.yixun.qfbao.model.dto.ApiLogDto;
import com.yixun.qfbao.model.dto.OtherCompanyDto;
import com.yixun.qfbao.model.enums.DelFlagEnum;
import com.yixun.qfbao.dao.ApiLogDao;
import com.yixun.qfbao.dao.OtherCompanyDao;
import com.yixun.qfbao.util.HttpApi;
import com.yixun.qfbao.util.email.MailConfig;
import com.yixun.qfbao.util.email.MailUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * 状态补发
 */
@Component
public class SendV10AgainJob {

    private static Logger logger = LoggerFactory.getLogger(SendV10AgainJob.class);

    @Autowired
    private OtherCompanyDao otherCompanyDao;

    @Autowired
    private ApiLogDao apiLogDao;

    @Autowired
    private MailConfig mailConfig;

    @Scheduled(cron = "0 0/1 * * * ?")
    public void sendV10Again() {
        List<ApiLog> logs = apiLogDao.listApiLogBySendV10Again();
        if (logs != null) {
            logger.info("sendV10Again ------------------ list count :" + logs.size());
            int count = 0;
            boolean mail;
            for (ApiLog log : logs) {
                mail = false;
                ApiLogDto newApiLog = new ApiLogDto();
                try {
                    if (StringUtils.isNotBlank(log.getUrl()) && StringUtils.isNotBlank(log.getRequestContent())) {
                        newApiLog.setOtherCompanyId(log.getOtherCompanyId());
                        newApiLog.setCompanyId(log.getCompanyId());
                        newApiLog.setPremisesId(log.getPremisesId());
                        newApiLog.setPremisesName(log.getPremisesName());
                        newApiLog.setOtherRelationId(log.getOtherRelationId());
                        newApiLog.setPartnerId(log.getPartnerId());
                        newApiLog.setPartnerName(log.getPartnerName());
                        newApiLog.setBusinessType(log.getBusinessType());
                        if (log.getRecordCount() != null) {
                            newApiLog.setRecordCount(log.getRecordCount() + 1);
                        } else {
                            newApiLog.setRecordCount(1);
                        }
                        OtherCompanyDto otherCompany = new OtherCompanyDto();
                        otherCompany.setIsDeleted(DelFlagEnum.UNDEL.getNo());
                        otherCompany.setCompanyUuid(log.getOtherCompanyId());
                        List<OtherCompany> otherCompanyList = otherCompanyDao.selectListByDto(otherCompany);
                        if (otherCompanyList == null || otherCompanyList.size() == 0) {
                            newApiLog.setRequestContent(log.getRequestContent());
                            newApiLog.setContent("公司相关信息为空,未发送请求");
                            newApiLog.setResponseContent("公司相关信息为空,未发送请求");
                            apiLogDao.create(newApiLog);
                            return;
                        }
                        String result = HttpApi.doPostV10(log.getUrl(), log.getRequestContent(),
                                otherCompanyList.get(0).getAppid(), otherCompanyList.get(0).getAppkey(),
                                otherCompanyList.get(0).getCompanyUuid(), newApiLog);
                        BaseResponseDto brDto = JSONObject.parseObject(result, BaseResponseDto.class);
                        if (StringUtils.equals(brDto.getResponseCode(), "1")) {
                            count++;
                        } else {
                            //超过3次 发邮件
                            if (newApiLog.getRecordCount() > 3) {
                                mail = false;
                            }
                        }
                    }
                } catch (Exception e) {
                    logger.error("sendV10Again error: {}", e);
                    newApiLog.setRequestContent(log.getRequestContent());
                    newApiLog.setContent(e.getMessage());
                    newApiLog.setResponseContent(e.getMessage());
                    apiLogDao.create(newApiLog);
                } finally {
                    ApiLogSendV10Again apiLogSendV10Again = new ApiLogSendV10Again();
                    apiLogSendV10Again.setApiId(log.getId());
                    apiLogSendV10Again.setCreateTime(new Date());
                    apiLogDao.addApiLogSendV10Again(apiLogSendV10Again);
                    if (mail) {
                        MailUtil.sendProcess(mailConfig, "min.zhu@qiaofang.cn", null, null, "[自动补推]同步V10报备状态失败", JSONObject.toJSONString(newApiLog), null);
                        MailUtil.sendProcess(mailConfig, "jianhua.song@qiaofang.cn", null, null, "[自动补推]同步V10报备状态失败", JSONObject.toJSONString(newApiLog), null);
                        MailUtil.sendProcess(mailConfig, "lei.tao@qiaofang.cn", null, null, "[自动补推]同步V10报备状态失败", JSONObject.toJSONString(newApiLog), null);
                        MailUtil.sendProcess(mailConfig, "dongyw@qiaofin.com", null, null, "[自动补推]同步V10报备状态失败", JSONObject.toJSONString(newApiLog), null);
                    }
                }
            }
            logger.info("sendV10Again ------------------ success count :" + count);
        }
    }

}
